package com.assessment.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.assessment.entity.Apply;
import com.assessment.service.ApplyService;
import com.assessment.service.Grade1Service;
import com.assessment.service.Grade2Service;
import com.assessment.service.Grade3Service;
import com.assessment.service.StaffService;
import com.assessment.util.ApplyUtil;

@Controller
@RequestMapping("/apply")
public class ApplyController {
	
	@Resource
	private ApplyService applyService;
	
	@Resource
	private StaffService staffService;
	
	@Resource
	private Grade1Service grade1Service;
	
	@Resource
	private Grade2Service grade2Service;
	
	@Resource
	private Grade3Service grade3Service;
	
	@RequestMapping("findAllApply.do")
	public String findAllApply(Model model){
		model.addAttribute("applylist", applyService.findAllApply());
		return "Grade/applylist";
	}
	
	@RequestMapping("toaddapply.do")
	public String toaddapply(){
		return "Grade/addapply";
	}
	
	@RequestMapping("addapply.do")
	public String addaply(String staff_name,String apply_jieduan,String apply_time,String reason,String apply_state) throws ParseException{
		int staffId=staffService.findStaffIdByStaffName(staff_name);
		//根据前端传过来的请假阶段转换成int类型
		int jieduan = 0;
		if("第一阶段".equals(apply_jieduan)){
			jieduan=1;
		}else if("第二阶段".equals(apply_jieduan)){
			jieduan=2;
		}else if("第三阶段".equals(apply_jieduan)){
			jieduan=3;
		}
		ApplyUtil applyUtil=new ApplyUtil();
		int state=applyUtil.applyState(apply_state);//根据传递过来的上午、下午、全天转换为1，2，3存入数据库
		if(jieduan==2){//如果是第二阶段请假，更新第二阶段成绩表
			if(state==3){//如果是请全天，调用加1的方法
				grade2Service.qingjia1(staffId);
			}else {//如果是半天，调用+0.5
				grade2Service.qingjia2(staffId);
			}
		}else if(jieduan==3){//如果是第三阶段请假，更新第三阶段成绩表
			if(state==3){//如果是请全天，调用加1的方法
				grade3Service.qingjia1(staffId);
			}else {//如果是半天，调用+0.5
				grade3Service.qingjia2(staffId);
			}
		}else{
			if(state==3){//如果是请全天，调用加1的方法
				grade1Service.qingjia1(staffId);
			}else {//如果是半天，调用+0.5
				grade1Service.qingjia2(staffId);
			}
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		Date date=format.parse(apply_time);
		Apply apply=new Apply(staffId, jieduan, date, state, reason);
		applyService.insertApply(apply);
		return "redirect:/apply/findAllApply.do";
	}

}
